#include<stdio.h>
#include<stdlib.h>
#define MAX 100
const int inf = 66666;
typedef struct GNode *PtrToGNode;
struct GNode{
    int v;  //顶点数
    int e;  //边数
    int g[100][100];
};
typedef PtrToGNode Graph;
bool vis[1000];   //访问标记
int n, m;

// 队列
typedef struct QNode *queue;
// front == rear 时候队列为空
struct QNode {
    int dat[MAX];
    int front;
    int rear;
};
queue CreateQueue(){
    queue q;
    q=(queue)malloc(sizeof(struct QNode));
    q->front = q->rear = 0;
    return q;
}
void addQueue(queue q,int data){
    q->dat[(q->rear)] = data;
    q->rear++;
    
}
int  delQueue(queue q){
    int x = q->dat[q->front];
    q->front++;
    return x;
}
bool isQueueEmpty(queue q){

    return q->front == q->rear ? true : false;
}

// 图
void init(){
    for (int i = 0; i <n;i++){
            vis[i] = false;
    }
}

Graph CreateGraph(){

    Graph G;

    G=(Graph)malloc(sizeof(struct GNode));
    G->v=n;
    G->e =m;

    for (int i = 0;i<n;i++){
        for (int j = 0;j<n;j++){
            G->g[i][j] = inf;
            
        }
    }
    init();
    return G;
}

void InsertEdge(Graph G,int a,int b,int w){

    G->g[a][b] = w; //有向图

}
void Visit(int v,FILE *fo){
    fprintf(fo, "%d ", v);
}
void BFS(Graph G,int k,FILE *fo){
    queue Q = CreateQueue();
    Visit(k,fo);
    vis[k] = true;
    addQueue(Q,k);

    while(!isQueueEmpty(Q)){
        int v = delQueue(Q);
     
        for (int i = 0; i < G->v ;i++){
             printf("%d %d",i,G->v);
            if((vis[i]==false) && (G->g[v][i]!=inf)){
            
                Visit(i,fo);
                vis[i] = true;
                addQueue(Q,i);
            

            }
    
        }
   
    }
}
int main(){
    
    FILE *fp,*fo;
    fp = fopen("in.txt", "r");
    fo = fopen("out.txt", "w");
    
    fscanf(fp, "%d", &n);
    fscanf(fp, "%d", &m);

    Graph G = CreateGraph();
    
    for (int i = 0; i < m;i++){
        int a, b, w;
        fscanf(fp, "%d %d %d", &a, &b, &w);
        InsertEdge(G,a, b, w);
    }
    int k;
    fscanf(fp, "%d", &k);
    while(k!=-1){
        init();
        fprintf(fo, "DFS From  %d : ",k);

        BFS(G,k,fo);

        fscanf(fp, "%d", &k);
        fprintf(fo, "\n");
    }
   
    fclose(fp);
    fclose(fo);
}